package com.my.app.document.model;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.annotation.AnnotationUtils;

import com.my.annotation.Model;
import com.my.annotation.Property;
import com.my.annotation.Remark;
import com.my.model.Request;
import com.my.toolkit.JsonUtil;
import com.my.utils.ClassUtil;
import com.my.utils.StringUtil;

import lombok.Data;

@Data
public class ApiParameter {

	private String name;
	private String description;
	private Class clazz;
	private Type type;
	private Map<String, ApiParameter> configChildren = new HashMap<String, ApiParameter>();// 特殊配置过的下级属性

	// 当dataType是复合类型,并且属性配置了remark才显示
	public List<ApiParameter> getChildren() {
		List list = new ArrayList();
		Class clazz = this.clazz;
		if (ClassUtil.isInstance(clazz, Collection.class)) {
			if (type != null) {
				clazz = ClassUtil.getGenericClass(type);
			}
		}

		for (Field f : clazz.getDeclaredFields()) {
			ApiParameter config = configChildren.get(f.getName());
			if (config != null) {
				list.add(config);
				continue;
			}

			Remark rmk = AnnotationUtils.findAnnotation(f, Remark.class);
			if (rmk != null) {
				String desc = rmk.value();
				if (StringUtil.isEmpty(desc)) {
					Property pp = AnnotationUtils.findAnnotation(f, Property.class);
					if (pp != null) {
						desc = pp.value();
					}
				}

				ApiParameter pa = new ApiParameter();
				pa.clazz = f.getType();
				pa.type = f.getGenericType();
				pa.description = desc;
				pa.name = f.getName();
				list.add(pa);
			}
		}

		return list;
	}

	public String getDataType() {
		if(type!=null) {
			return type.getTypeName();
		}
		return clazz.getName();
	}

	public String getDescription() {
		if (!StringUtil.isEmpty(description)) {
			return description;
		}

		Model mod = (Model) clazz.getAnnotation(Model.class);
		if (mod == null) {
			return "";
		}
		return mod.value();
	}

	//返回json格式的参数
	public String getJson() {
		Class clazz = this.clazz;
		if (ClassUtil.isInstance(clazz, Collection.class)) {
			if (type != null) {
				clazz = ClassUtil.getGenericClass(type);
			}
			Object o=ClassUtil.newInstance(clazz);
			List list=new ArrayList();
			list.add(o);
			return JsonUtil.NULL.toFormatString(list);
		}
		Object o=ClassUtil.newInstance(clazz);
		if(o instanceof Request) {
			ApiParameter contentPa=configChildren.get("content");
			if(contentPa==null) {
				return JsonUtil.NULL.toString(o);
			}
			
			Object content=ClassUtil.newInstance(contentPa.getClazz());
			Request request=(Request)o;
			
			request.setContent(content);
		}
		return JsonUtil.NULL.toFormatString(o);
		
	}

}
